// packageActivity/pages/posters-work/posters-work.js
import user from '../../../utils/user.js'
import {
	queryUserReport
} from '../../api/activity'
import {
	dybbAd
} from '../../../api/app.js'
import dayjs from 'dayjs'
import {
	base64ToWxfile,
	wxfileTobase64,
	wait,
	toast
} from '../../../utils/util.js'
import {
	generateQrCode,
	preciseExtension,
	getQrcodeInfo,
	createPrecise
} from "../../api/activity.js"
import {
	createClientQrCode,
	getUserAvatar,
	getEnterpriseList
} from '../../../api/app.js'
import Canvas from '../../../utils/canvas'

Page({
	data: {
		selectTypeList: [{
			text: '全选',
			callback: 'selectAll'
		}],
		posterList: [],
		qrcode: '',
		QrCode: '',
		isPoster: false,
		currentIndex: 0,
		wholePopup: false,
		isAlonePopup: false,
		avatarUrl: '',
		userName: '',
		enterprise: {
			name: '',
			code: '',
			phone: '',
			userName: '',
			id: '',
			qrId: '',
			area: ''
		},
		tipList: "",
		isSendOutBtn: false,
		qrId: '', //二维码id
		json: {
			invitationCount: {
				name: '总招人：',
				value: 0,
				cacheValue: 0,
				unit: '人',
				x: 20,
				isOpenEye: true,
				y: 270,
				color: '#014C70',
				valueColor: '#014C70',
				fontSize: 16,
				offsetX: 25,
				areaX: 120,
				offsetY: 85,
				areaY: 30,
				nameWidth: 70,
				valueWidth: 100
			},
			salaryPaymentCount: {
				name: '总发薪：',
				value: 0,
				cacheValue: 0,
				unit: '笔',
				x: 20,
				isOpenEye: true,
				y: 305,
				color: '#014C70',
				valueColor: '#014C70',
				fontSize: 16,
				offsetX: 25,
				areaX: 120,
				offsetY: 85,
				areaY: 30,
				nameWidth: 70,
				valueWidth: 100
			},
			insureApplicationCount: {
				name: '累计投保：',
				value: 0,
				cacheValue: 0,
				unit: '笔',
				x: 20,
				isOpenEye: true,
				y: 340,
				color: '#014C70',
				valueColor: '#014C70',
				fontSize: 16,
				offsetX: 25,
				areaX: 120,
				offsetY: 85,
				areaY: 30,
				nameWidth: 80,
				valueWidth: 100
			},
			approvalCount: {
				name: '处理审批：',
				value: 0,
				cacheValue: 0,
				unit: '条',
				x: 20,
				isOpenEye: true,
				y: 375,
				color: '#014C70',
				valueColor: '#014C70',
				fontSize: 16,
				offsetX: 25,
				areaX: 120,
				offsetY: 85,
				areaY: 30,
				nameWidth: 80,
				valueWidth: 100
			}
		},
		bgList: [
			'/packageActivity/assets/img/annul/sbg.png',
			'/packageActivity/assets/img/annul/sbg.png',
		],
		isOpenEye: false
	},
	async onLoad(options) {
		wx.loadFontFace({
			family: 'Heavy',
			source: 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file-font/Heavy.subset.ttf',
			success: function (e) {
				console.log('success', e);
			},
			error: function (e) {
				console.log('error', e);
			},
		})
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
		user.waitLogin().then(async () => {
			await this.createInviteQrCode()
			this.setData({
				avatarUrl: user.avatarUrl,
				userName: user.userName
			})
			if (!user.isSuperAdmin) {
				this.data.json.latestWorkingHour = {
					name: '最晚工作时间：',
					value: '',
					cacheValue: 3213,
					unit: '',
					x: 20,
					isOpenEye: true,
					y: 410,
					color: '#014C70',
					valueColor: '#014C70',
					fontSize: 16,
					offsetX: 25,
					areaX: 120,
					offsetY: 85,
					areaY: 30,
					nameWidth: 110,
					valueWidth: 80
				}
				this.setData({
					json: this.data.json
				})
			}
			this.getData()
		})
	},
	onReady() {

	},
	onShow: function () {

	},
	getData() {
		queryUserReport({}).then(res => {
			for (const key in this.data.json) {
				this.data.json[key].value = res[key] ?? ''
				this.data.json[key].cacheValue = res[key] ?? ''
			}
			if (!user.isSuperAdmin && res.latestWorkingHour) {
				this.data.json.latestWorkingHour.value = dayjs(res.latestWorkingHour).format('HH:mm')
				this.data.json.latestWorkingHour.cacheValue = dayjs(res.latestWorkingHour).format('HH:mm')
			}
			this.setData({
				json: this.data.json
			})
		})
	},
	onNameInput(event) {
		const {
			value
		} = event.detail
		this.setData({
			['enterprise.userName']: value
		})
	},
	onPhoneInput(event) {
		const {
			value
		} = event.detail
		this.setData({
			['enterprise.phone']: value
		})
	},
	onEnterpriseInput(event) {
		const {
			value
		} = event.detail
		getEnterpriseList({
			name: value
		}).then(res => {
			this.setData({
				tipList: res
			})
		})
	},
	onTapEnter(event) {
		console.log(event, 'event')
		const {
			name,
			code,
			area
		} = event.currentTarget.dataset
		this.setData({
			['enterprise.name']: name,
			['enterprise.code']: code,
			['enterprise.area']: area,
			tipList: [],
			isSendOutBtn: true
		})
		console.log(this.data.isSendOutBtn, 'isSendOutBtn')
	},
	isSendOut() {
		if (this.data.enterprise.userName && this.data.enterprise.phone && this.data.enterprise.code) {
			this.setData({
				isSendOutBtn: true
			})
			console.log(this.data.isSendOutBtn)
		}
	},
	onPreciseExtension() {
		if (!this.data.enterprise.userName) {
			toast('请填写姓名')
			return
		}
		if (!this.data.enterprise.phone) {
			toast('请填写手机号')
			return
		}
		if (!this.data.enterprise.code) {
			toast('请选择公司或检查公司是否存在')
			return
		}
		createPrecise({
			contactName: this.data.enterprise.userName,
			contactPhone: this.data.enterprise.phone,
			customName: this.data.enterprise.name,
			creditCode: this.data.enterprise.code,
			area: this.data.enterprise.area
		}).then(res => {
			this.ndzdbg()
			this.setData({
				['enterprise.id']: res.id
			})
			wx.navigateTo({
				url: '/packageActivity/pages/annually-success/annually-success',
				success: (res) => {
					res.eventChannel.emit('acceptDataFromOpenerPage', {
						data: this.data.enterprise,
						type: 'alone'
					})
					this.cancel()
				}
			})
		})
	},
	onSwiperChange(event) {
		console.log(event.detail.current, 'event')
		this.setData({
			currentIndex: event.detail.current
		})
	},
	onAloneSendout() {
		this.setData({
			isAlonePopup: true
		})
	},
	cancel() {
		this.setData({
			isAlonePopup: false
		})
	},
	onWholeDisplay() {
		this.setData({
			wholePopup: true
		})
	},
	onWholeHide() {
		this.setData({
			wholePopup: false
		})
	},
	createInviteQrCode() {
		getQrcodeInfo({
			page: 'packageActivity/pages/spread/spread',
			width: 100
		}).then(res => {
			this.setData({
				['enterprise.qrId']: res.qrId,
				qrId: res.qrId
			})
			let qrCode = JSON.parse(res.qrbody).data // 后台返回的base64图片流
			this.setData({
				QrCode: `data:image/png;base64,${qrCode}`
			})
			base64ToWxfile(qrCode, Math.ceil(Math.random() * 10000000000) + '.png').then(path => {
				this.setData({
					qrcode: path
				}, () => {
					console.log(this.data.qrcode, 'qrcode')
				})
				// this.saveQrCode()
			})
		})
	},
	handleCanvasClick(ev) {
		console.log(1111, ev.detail);
	},
	roundRect(ctx, x, y, w, h, r) {
		// 开始绘制 
		ctx.beginPath()
		// 因为边缘描边存在锯齿，最好指定使用 transparent 填充 
		// 这里是使用 fill 还是 stroke都可以，二选一即可 
		// ctx.setFillStyle('transparent') 
		// ctx.setStrokeStyle('transparent')
		// 左上角 
		ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
		// border-top ctx.moveTo(x + r, y) 
		ctx.lineTo(x + w - r, y)
		ctx.lineTo(x + w, y + r)
		// 右上角
		ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
		// border-right 
		ctx.lineTo(x + w, y + h - r)
		ctx.lineTo(x + w - r, y + h)
		// 右下角
		ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
		// border-bottom 
		ctx.lineTo(x + r, y + h)
		ctx.lineTo(x, y + h - r)
		// 左下角 
		ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
		// border-left
		ctx.lineTo(x, y + r)
		ctx.lineTo(x + r, y)
		// 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应 c
		ctx.fillStyle = '#ffffff'
		ctx.fill()
		// ctx.stroke()
		ctx.closePath()
		// 剪切 
		ctx.clip()
	},
	drawRectImage(canvas, path) {
		return new Promise(resolve => {
			const img = canvas.createImage()
			img.src = path
			img.onload = () => {
				resolve(img)
			}
		})
	},
	saveQrCode(id, bg) {
		return new Promise(async (resolve) => {
			// let bg = [
			// 	'/packageActivity/assets/img/annul/sbg.png',
			// 	'/packageActivity/assets/img/annul/sbg-1.png',
			// ]
			this.data.posterList = []
			const result = await getUserAvatar({
				userId: user.userId
			})
			console.log(888, result);
			const path = result ? `data:image/png;base64,${result}` : '/assets/img/avatar.png'
			this.setData({
				avatar: path
			})
			// const path = await base64ToWxfile(result, 'avatar.png')
			// this.setData({
			// 	avatarUrl: path
			// }, () => {
			// 	console.log(this.data.avatarUrl, 'avatarUrl')
			// })

			// this.setData({
			//     avatarUrl:(base64 === 'undefind' || !base64) ? '/assets/img/avatar.png' : res
			// }) = (base64 === 'undefind' || !base64) ?
			// bg.forEach(async (i, index) => {

			wx.createSelectorQuery()
				.select(id) // 在 WXML 中填入的 id
				.fields({
					node: true,
					size: true
				})
				.exec(async (res) => {
					// for (const index in bg) {
					wx.showLoading({
						mask: true,
						title: '正在渲染中...'
					})
					// Canvas 对象


					const canvas = res[0].node
					// 渲染上下文
					const ctx = canvas.getContext('2d')

					// Canvas 画布的实际绘制宽高
					const width = res[0].width
					const height = res[0].height

					// 初始化画布大小
					const dpr = wx.getWindowInfo().pixelRatio
					canvas.width = width * dpr
					canvas.height = height * dpr
					ctx.scale(dpr, dpr)
					await wait(300)
					// ctx.rect(0, 0, 320, 500, 10)
					// this.roundRect(ctx, 0, 0, 320, 500, 10)
					// ctx.fill()

					// const background = canvas.createImage()
					// background.src = bg[index]
					// background.onload = async () => {
					// ctx.drawImage(background, 20, 20, 280, 320)
					// 背景图
					let img = await this.drawRectImage(canvas, bg)
					ctx.drawImage(img, 0, 0, 323, 536)
					// 头像
					let avatar = await this.drawRectImage(canvas, path)
					const x = 15
					const y = 180
					const w = 60
					ctx.save()
					ctx.beginPath()
					ctx.arc(x + w / 2, y + w / 2, w / 2, 0, Math.PI * 2, false)
					ctx.closePath()
					ctx.fill()
					ctx.clip()
					ctx.drawImage(avatar, x, y, w, w)
					ctx.restore()
					await wait(100)
					// 姓名
					ctx.font = '16px normal'
					ctx.fillStyle = '#014C70'
					ctx.fillText(user.userName, 90, 215, 100)
					// 欢迎语
					ctx.font = '16px bold'
					ctx.fillStyle = '#fff'
					ctx.fillText('Hi～我在子弹发薪', 20, 485, 200)
					ctx.fillText('最好用的劳务派遣线上平台', 20, 510, 200)
					if (id === '#poster') {
						for (const key in this.data.json) {
							ctx.font = `16px normal`
							ctx.fillStyle = this.data.json[key].color
							ctx.fillText(this.data.json[key].name, this.data.json[key].x, this.data.json[key].y)
							ctx.font = `22px bold Heavy`
							ctx.fillStyle = this.data.json[key].valueColor
							ctx.fillText(this.data.json[key].value + this.data.json[key].unit, this.data.json[key].x + this.data.json[key].nameWidth, this.data.json[key].y)
						}
					} else if (id === '#poster1') {
						ctx.font = '14px normal'
						ctx.fillStyle = '#014C70'
						ctx.fillText('无卡发薪', 20, 330, 100)
						ctx.fillText('电子考勤', 97, 330, 100)
						ctx.fillText('预支薪资', 171, 330, 100)
						ctx.fillText('快速招聘', 247, 330, 100)
						ctx.fillText('用工排班', 59, 420, 100)
						ctx.fillText('电子合同', 134, 420, 100)
						ctx.fillText('日结保险', 209, 420, 100)
					}
					// 二维码
					const qrCode = await this.drawRectImage(canvas, this.data.QrCode)
					this.roundRect(ctx, 240, 454, 76, 76, 10)
					ctx.drawImage(qrCode, 243, 455, 72, 72)
					ctx.restore()
					await wait(100)

					await wx.canvasToTempFilePath({
						canvas,
						success: async (res) => {
							await wxfileTobase64(res.tempFilePath, true).then(async url => {
								// console.log(url,'url')
								let arr = []
								arr = this.data.posterList
								arr.push({
									path: res.tempFilePath,
									src: url
								})

								// if (arr.length === bg.length) {
								wx.hideLoading()
								resolve(arr)
								// }
								this.setData({
									posterList: arr,
								}, () => {
									// console.log(this.data.posterList,'posterList')
								})
							})
						},
					})
					// }
					// }
					// }
				})
		})
	},
	// 图片保存
	async savecanvas(success, fail) {
		const idx = this.data.currentIndex
		let list = []
		if (idx === 0) {
			list = await this.saveQrCode('#poster', '/packageActivity/assets/img/annul/sbg.png')
		} else if (idx === 1) {
			list = await this.saveQrCode('#poster1', '/packageActivity/assets/img/annul/sbg-1.png')
		}
		wx.saveImageToPhotosAlbum({
			filePath: list[0].path,
			success: (res) => {
				toast(success)
				this.setData({
					wholePopup: false
				})
			},
			fail: (rej) => {
				toast(fail)
			}
		})
	},
	preservation() {
		this.ndzdbg()
		this.savecanvas('保存成功', '保存失败')
	},
	onToBrother() {
		this.ndzdbg()
		this.savecanvas('保存成功，请自行发送到朋友圈', '保存失败')
	},
	onShareAppMessage() {
		// scene path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId),
		return {
			title: '「' + user.userName + '」' + ' 邀请您使用子弹发薪',
			path: '/packageActivity/pages/spread/spread?scene=' + encodeURIComponent('QRID=' + this.data.qrId),
			imageUrl: '/packageActivity/assets/img/poster/invite.png'
		}
	},
	// handleClick(ev) {
	// 	const pos = ev.detail
	// 	let inArea = false
	// 	let windowWidth = wx.getSystemInfoSync().windowWidth
	// 	let windowHeight = wx.getSystemInfoSync().windowHeight
	// 	console.log(111, pos, windowHeight);
	// 	console.log(222, windowWidth);
	// 	for (const key in this.data.json) {
	// 		const cur = this.data.json[key]
	// 		console.log(444, cur);
	// 		if (pos.x >= parseInt(windowWidth * 0.83) && pos.x < parseInt(windowWidth * 0.90)  && pos.y >= cur.y + cur.offsetY && pos.y < cur.y + cur.offsetY + cur.areaY) {
	// 			cur.value = cur.value === '***' ? cur.cacheValue : '***'
	// 			inArea = true
	// 		}
	// 	}
	// 	if (inArea) {
	// 		setTimeout(() => {
	// 			this.saveQrCode()
	// 		}, 100);
	// 	}
	// },
	toggleEye(ev) {
		const dataset = ev.currentTarget.dataset
		this.data.json[dataset.index].value = this.data.json[dataset.index].value === '***' ? this.data.json[dataset.index].cacheValue : '***'
		this.data.json[dataset.index].isOpenEye = !this.data.json[dataset.index].isOpenEye
		this.setData({
			json: this.data.json,
		})
	},
	ndzdbg() {
		dybbAd({
			isShare: 1,
			isExposure: 0,
			type: 1,
		}).then((res) => {
			console.log(res, 'fgasgyfjiusagygyasu');
		})
	},
	doShare() {
		this.ndzdbg()
	}
})